package cn.hbads.support.context;

import cn.hbads.support.error.CommonErrorType;
import cn.hbads.support.error.ErrorType;
import cn.hbads.support.structure.result.ComputeResult;
import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
@Getter
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static boolean isAwareSuccess() {
        return applicationContext != null;
    }

    public static <T> ComputeResult<T, ErrorType> getBean(Class<T> clazz) {
        if (!isAwareSuccess()) {
            return ComputeResult.fail(CommonErrorType.CONTEXT_INSTANCE_NOT_INITIALIZED);
        }
        try {
            return ComputeResult.success(applicationContext.getBean(clazz));
        } catch (BeansException exception) {
            return ComputeResult.fail(CommonErrorType.APPLICATION_GET_BEAN_ERROR, exception);
        }
    }

    public static <T> ComputeResult<T, ErrorType> getBean(String beanName, Class<T> requiredType) {
        if (!isAwareSuccess()) {
            return ComputeResult.fail(CommonErrorType.CONTEXT_INSTANCE_NOT_INITIALIZED);
        }
        try {
            return ComputeResult.success(applicationContext.getBean(beanName, requiredType));
        } catch (BeansException exception) {
            return ComputeResult.fail(CommonErrorType.APPLICATION_GET_BEAN_ERROR, exception);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }
}
